package com.icesoft.core.web.configurer.tomcat;

import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;
import org.apache.catalina.valves.ErrorReportValve;
import org.apache.tomcat.util.ExceptionUtils;

import java.io.IOException;
import java.io.Writer;

/**
 * tomcat的404错误自动重定向到contextPath的404页面
 *
 * @author XHH
 * @date 2021/1/21 16:15
 */
public class Redirect404ErrorReportValue extends ErrorReportValve {
    private final String page404;

    Redirect404ErrorReportValue(String contextPath) {
        String contextPathPre;
        if ("/".equals(contextPath)) {
            contextPathPre = contextPath;
        } else {
            contextPathPre = contextPath + "/";
        }
        this.page404 = "<html><head> <meta http-equiv='refresh' content='0;url=" +
                contextPathPre +
                "error/404.html'></head><body></body></html>";
    }

    @Override
    protected void report(Request request, Response response, Throwable throwable) {
        if (response.getStatus() == 404) {
            try {
                try {
                    response.setContentType("text/html");
                    response.setCharacterEncoding("utf-8");
                } catch (Throwable var27) {
                    ExceptionUtils.handleThrowable(var27);
                    if (this.container.getLogger().isDebugEnabled()) {
                        this.container.getLogger().debug("status.setContentType", var27);
                    }
                }

                Writer writer = response.getReporter();
                if (writer != null) {
                    writer.write(page404);
                    response.finishResponse();
                }
            } catch (IOException var28) {
            } catch (IllegalStateException var29) {
            }
        } else {
            super.report(request, response, throwable);
        }

    }
}
